import getopt
import getpass
import sys

import gdata.apps.service


class TogglePasswordChangeSample(object):

	def __init__(self,admin_account,admin_password,domain):
		self.client = gdata.apps.service.AppsService()
		self.client.domain = domain
		self.client.email = admin_account
		self.client.password = admin_password
		self.client.ProgrammaticLogin()


	def Run(self):
		# Retrieve all users
		userList = self.client.RetrieveAllUsers()

		# Iterate through UserFeed object
		for userEntry in userList.entry:
			print
			if (userEntry.login.change_password == "true"):
				userEntry.login.change_password = "false"

				print 'Turning off "force password change option" for user: ' +  userEntry.login.user_name
				try:
					self.client.UpdateUser(userEntry.login.user_name, userEntry)
				except:
					print 'There was an error updating setting for user: ' + userEntry.login.user_name
					print self.client.Error
								
			else:
				print  userEntry.login.user_name + ' does not have "force password change option" activated'
	
def main():
# Command line Parameters:
	try:
		opts, args = getopt.getopt(sys.argv[1:], '', ['admin_account=', 'admin_password=', 'domain='])
	except getopt.error, msg:
		print 'python togglePasswordChangeOff.py --admin_account [admin account name] --admin_password [password]'
		print ' --domain [yourdomain.com]'
		sys.exit(2)

	admin_account = ''
	admin_password = ''
	domain = ''

	# Process the Command Line Args
	for option, arg in opts:
		if option == '--admin_email':
			admin_email = arg
		elif option == '--admin_password':
 			admin_password = arg
		elif option == '--domain':
			domain = arg

	# Make sure input parameters are available
	while not domain:
		domain = raw_input('Enter your Google Apps domain (i.e. "yourname.com"): ')
	while not admin_account:
		admin_account = raw_input('Enter a administrator account: ')+'@'+domain
	while not admin_password:
		admin_password = getpass.getpass('Enter the admin account password: ')
	if not admin_password:
		print 'Password cannot be blank'
 
	# Authenticate the password toggle service
	try:
		passwordToggleService = TogglePasswordChangeSample(admin_account, admin_password, domain)
	except gdata.service.BadAuthentication:
		print 'Invalid user credentials given.'
		return

	passwordToggleService.Run()
 
if __name__ == "__main__":
    main()
